package com.fgba.express.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fgba.express.comm.GlobalConst;
import com.fgba.express.comm.enums.State;
import com.fgba.express.comm.exception.BizException;
import com.fgba.express.comm.result.ResultCode;
import com.fgba.express.core.controller.BaseController;
import com.fgba.express.data.dto.MenuDto;
import com.fgba.express.data.dto.UserDto;
import com.fgba.express.data.entity.Role;
import com.fgba.express.data.entity.User;
import com.fgba.express.data.entity.UserRoleMapping;
import com.fgba.express.data.mapstruct.UserStruct;
import com.fgba.express.data.search.UserSearch;
import com.fgba.express.data.service.IMenuService;
import com.fgba.express.data.service.IRoleService;
import com.fgba.express.data.service.IUserRoleMappingService;
import com.fgba.express.data.service.IUserService;
import com.fgba.express.util.BeanContextUtil;
import com.fgba.express.util.CheckEntityUtil;
import com.fgba.express.util.NullChecker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author fgba
 * @since 2022-02-24
 */
@RestController
@RequestMapping("/security/user")
@Api(value = "用户相关操作", tags = "用户相关操作")
public class UserController extends BaseController<User, UserDto, UserSearch, IUserService, UserStruct> {
    @Resource
    IUserRoleMappingService userRoleMappingService;

    @Override
    public void createValidation(UserDto model) {
        if (NullChecker.isNullOrEmpty(model.getUsername())) {
            log.error("RoleController -> save: username is null");
            throw new BizException(ResultCode.USER_REQUEST_PARAM_IS_BLANK);
        }

        if (NullChecker.isNullOrEmpty(model.getPhone())) {
            log.error("RoleController -> save: phone is null");
            throw new BizException(ResultCode.USER_REQUEST_PARAM_IS_BLANK);
        }

        if (NullChecker.isNull(model.getRoleIds())) {
            log.error("RoleController -> save: roleIds is null");
            throw new BizException(ResultCode.USER_REQUEST_PARAM_IS_BLANK);
        }
    }

    /**
     * 用户重置密码
     *
     * @return
     */
    @ApiOperation(value = "用户重置密码", notes = "用户重置密码")
    @PostMapping("/password/{id}")
    public void resetPassword(@PathVariable Long id) {
        User user = new User();
        user.setId(id);
        user.setPassword(BeanContextUtil.getBean(PasswordEncoder.class).encode(GlobalConst.DEFAULT_PASSWORD));
        service.updateById(user);
    }

    @PostMapping("/logout")
    @ApiOperation(value = "微信用户注销")
    @Transactional(rollbackFor = Exception.class)
    void weChatLogout(Principal principal) {
        User user = this.getUser(principal);
        user.setWxId(null);
        if (service.updateById(user)) {
            throw new BizException(ResultCode.HANDLE_FAIL);
        }
    }

    /**
     * 查询当前用户信息
     *
     * */
    @GetMapping("info")
    @ApiOperation(value = "查询当前用户信息")
    @Transactional(readOnly = true)
    public UserDto getCurrentUser(Principal principal) {
        User user = this.getUser(principal);
        UserDto userDto = struct.dtoConvertEntity(user);
        List<MenuDto> navMenus = BeanContextUtil.getBean(IMenuService.class).getNavMenus(user.getId());
        userDto.setAccess(navMenus.stream().map(MenuDto::getPerms).collect(Collectors.toList()));
        return userDto;
    }

    /**
     * 查询当前用户菜单
     *
     * */
    @GetMapping("menu")
    @ApiOperation(value = "查询当前用户菜单")
    @Transactional(readOnly = true)
    public List<MenuDto> getCurrentUserMenu(Principal principal) {
        User user = this.getUser(principal);

        List<MenuDto> navMenus = BeanContextUtil.getBean(IMenuService.class).getNavMenus(user.getId());
        return navMenus;
    }
    /**
     * 获取首页用户统计数据
     *
     * @return
     */
    @ApiOperation(value = "获取首页用户统计数据", notes = "获取首页用户统计数据")
    @GetMapping("/homeData")
    @PreAuthorize("isAuthenticated()")
    public Map<String, Object> getHomeData() {
        LocalDate today = LocalDate.now();
        int weekDay = today.getDayOfWeek().getValue();
        //本周的第一天
        LocalDate weekFirstDay = today.minus(weekDay, ChronoUnit.DAYS);
        Map<String, Object> data = new HashMap<>(3);
        List<Integer> registeredUsersWeekData = new LinkedList<>();
        int registeredUsersWeekTotal = 0;

        for (int i = 0; i < GlobalConst.WEEK_DAY; i++) {
            //统计从周一开始，每次循环添加到下一天
            LocalDate day1 = weekFirstDay.plus(i, ChronoUnit.DAYS);
            LocalDate day2 = weekFirstDay.plus(i + 1, ChronoUnit.DAYS);
            //今天之后的数据不统计
            if (today.isBefore(day1)) {
                break;
            }
            int registeredUsersNum = service.count(Wrappers.<User>lambdaQuery().ge(User::getCreateTime, day1).lt(User::getCreateTime, day2));
            registeredUsersWeekTotal += registeredUsersNum;
            registeredUsersWeekData.add(registeredUsersNum);
        }
        data.put("registeredUsersWeekData", registeredUsersWeekData);
        data.put("registeredUsersWeekTotal", registeredUsersWeekTotal);
        data.put("registeredUsersTotal", service.count(Wrappers.<User>lambdaQuery().eq(User::getState, State.STATUS_AVAILABLE)));

        return data;
    }

    @Override
    public void afterEdit(UserDto model) throws Exception {
        List<UserRoleMapping> userRoleMappings = userRoleMappingService.list(Wrappers.<UserRoleMapping>lambdaQuery().eq(UserRoleMapping::getUserId, model.getId()));
        List<Long> roleIds = userRoleMappings.stream().map(UserRoleMapping::getRoleId).collect(Collectors.toList());
        model.setRoleIds(roleIds);
    }

    @Override
    public void beforeSave(UserDto model) throws Exception {
        if (NullChecker.isNullOrEmpty(model.getPassword())) {
            model.setPassword(BeanContextUtil.getBean(PasswordEncoder.class).encode(GlobalConst.DEFAULT_PASSWORD));
        }
    }

    @Override
    public void afterSave(UserDto model) throws Exception {
        saveUserRole(model);
        BeanContextUtil.getBean(IUserService.class).clearUserAuthorityInfo(model.getUsername());
    }

    @Override
    public void afterUpdate(UserDto model) throws Exception {
        if (!NullChecker.isNull(model.getRoleIds())) {
            saveUserRole(model);
            BeanContextUtil.getBean(IUserService.class).clearUserAuthorityInfo(service.getById(model.getId()).getUsername());
        }
    }

    private void saveUserRole(UserDto model) {
        List<UserRoleMapping> userRoleMappings = new LinkedList<>();
        if (NullChecker.isNull(model.getRoleIds())) {
            throw new BizException("参数错误");
        }
        for (Long roleId : model.getRoleIds()) {
            UserRoleMapping userRoleMapping = new UserRoleMapping();
            userRoleMapping.setUserId(model.getId());
            userRoleMapping.setRoleId(roleId);
            userRoleMappings.add(userRoleMapping);
        }
        userRoleMappingService.remove(Wrappers.<UserRoleMapping>lambdaQuery().eq(UserRoleMapping::getUserId, model.getId()));
        userRoleMappingService.saveBatch(userRoleMappings);
    }
    protected User getUser(Principal principal) {
        boolean isWx = requestFormIsWx();
        User user;
        IUserService userService = BeanContextUtil.getBean(IUserService.class);
        if (isWx) {
            user = CheckEntityUtil.isNullByColumnEq("wx_id",principal.getName(), userService, ResultCode.SYSTEM_RESOURCE_ERROR);
        } else {
            user = CheckEntityUtil.isNullByColumnEq("username",principal.getName(),userService, ResultCode.SYSTEM_RESOURCE_ERROR);
        }
        user.setPassword(null);
        return user;
    }
}
